<script setup lang="ts">
import { computed, watch } from 'vue'
import ListSearch from './ListSearch.vue'
import { useStore } from 'vuex'
import { refreshLastRead } from '../api/cache'

const store = useStore()
const resentList = computed(() => store.getters.getResentMessageList)
const lastReadCount = computed(() => store.getters.getLastReadCount)

watch([lastReadCount, resentList], () => {
  if (lastReadCount.value > 0) {
    store.commit('SET_NEW_MESSAGE_NOTIFICATION', true)
  } else {
    store.commit('SET_NEW_MESSAGE_NOTIFICATION', false)
  }
})

const emit = defineEmits(['show-resent-msg'])

const showResentMsg = (index: number, id: number, userId: number, msgId: string) => {
  emit('show-resent-msg', userId)

  refreshLastRead(id, store.getters.getUserId, msgId)

  if (!resentList.value[index].isLastRead) {
    resentList.value[index].isLastRead = true
    store.commit('DECREASE_LAST_READ_COUNT')
  }

  store.commit('SET_ACTIVE_INDEX', msgId)
}
</script>

<template>
  <div class="h-full flex flex-col divide-y divide-slate-300">
    <list-search />
    <div class="w-full overflow-y-auto" style="height: 636px">
      <ul class="flex flex-col h-full w-full list-none">
        <li
          v-for="(item, index) in resentList"
          :key="index"
          class="flex w-full pt-2 pl-2 pr-2 pb-2 hover:cursor-pointer hover:bg-gray-300 resent-list"
          :class="{ 'bg-gray-300': store.getters.getActiveIndex === item.msgId }"
          @click="showResentMsg(index, item.id, item.userId, item.msgId)"
        >
          <img
            :src="item.avatar"
            alt="Avatar"
            class="w-10 h-10 rounded-full mr-3 object-scale-down"
          />
          <div class="flex flex-col items-start" style="width: 125px">
            <div class="mb-1">
              <p
                class="font-semibold text-sm overflow-ellipsis whitespace-nowrap overflow-hidden"
                style="width: 140px; text-align: left"
                v-html="item.nickname"
              ></p>
            </div>
            <div style="max-height: 16px; overflow-y: hidden">
              <p
                class="text-xs text-gray-500 overflow-ellipsis whitespace-nowrap overflow-hidden"
                style="width: 140px; text-align: left"
                v-html="item.content"
              ></p>
            </div>
          </div>
          <el-badge class="m-auto" :is-dot="!item.isLastRead"></el-badge>
        </li>
      </ul>
    </div>
  </div>
</template>

<style scoped></style>
